package com.zhongshan.ga.mobile.resource;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.restlet.ext.fileupload.RestletFileUpload;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.restlet.resource.ResourceException;
import org.restlet.resource.ServerResource;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.zhongshan.ga.commonvar.ArgsConfig;
import com.zhongshan.ga.commonvar.PHPWebUrl;
import com.zhongshan.ga.logger.GenerateLog;

/**
 * 保存结伴游图片
 * @author yanqi
 *
 */
public class SaveTravelMateImgResource extends ServerResource{
	/**
	 * 上传图片的用户ID
	 */
	private String userId;
	
	// 新的图片名称 
	private String imgName;

	@Override
	protected void doInit() throws ResourceException {
		// TODO Auto-generated method stub
		userId = (String) getRequestAttributes().get("userId");
	}
	
	@Get
	public Representation getTravelMateImg(Representation representation) throws IOException {
		GenerateLog.outDebug("调用保存结伴游的方法");
		representation = postTravelMateImg(representation);
		return representation;
	}
	
	@Post
	public Representation postTravelMateImg(Representation representation) throws IOException{
		GenerateLog.outDebug("调用保存结伴游的方法");
		GenerateLog.outDebug(representation);
		try {
			System.out.println(SaveTravelMateImgResource.class.getClassLoader()
					.getResource("../../").toString());
			
			GenerateLog.outDebug("starting setTravelMateImage......");
			DiskFileItemFactory factory = new DiskFileItemFactory();
			System.out.println("starting upload......");

			RestletFileUpload upload = new RestletFileUpload(factory);
			List<FileItem> items = null;
			try {
				items = upload.parseRepresentation(representation);
				System.out.println(items.size() + "..................");
			} catch (Exception e) {
				// TODO: handle exception
			}
			String filename = "";
			// 路径 pathString = http://192.168.1.102:81/appimages/  ==》D:\Andrew\GuideAssistanceAPPImages
			// String pathString = PHPWebUrl.ARTIFACT_COVER_IMAGES_URL;
			
			// 这个为图片存放的图片物理路径（即为PHP服务器中指定的虚拟路径）
			String pathString = ArgsConfig.SAVE_IMAGE_PATH;
			
			int index = 0;
			ArrayList<String> imageArrayList = new ArrayList<String>();
			for (FileItem fi : items) {
				// 获得文件名
				String fileName = fi.getName();
				//String fileName = fi.getName();
				System.out.println(pathString + fileName+"名字。。。。。。");
				 filename = fi.getFieldName();
				System.out.println((fi == null) + "Save image ... " + filename);
				
				String type = fi.getContentType();
				long size = fi.getSize();
				System.out.println(type + size);
				
				imgName = System.currentTimeMillis()
						+ "-"+userId
						+ fileName;
				String newName = pathString+imgName;
				index++;
				File file = new File(newName);
				GenerateLog.outDebug(pathString + newName);
				if (!file.exists()) {// 判断文件是否存在
					try {
						file.createNewFile();// 创建文件
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				try {
					fi.write(file);
					imageArrayList.add(imgName);
					GenerateLog.outDebug(new Gson().toJson(imageArrayList));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			// 图片列表
			//JsonArray imageJsonArray = new JsonParser().parse(new Gson().toJson(imageArrayList)).getAsJsonArray();
			JsonObject object = new JsonObject();
			object.addProperty(ArgsConfig.RESULT_CODE, ArgsConfig.RESPONSE_SUCCESS);
			object.addProperty(ArgsConfig.RESULT_DESC, "上传成功");
			object.addProperty(ArgsConfig.IMAGE_NAME, imgName);
			System.out.println(object.toString());
			
			GenerateLog.outDebug(object.toString());
			return new StringRepresentation(object.toString());
		} catch (Exception e) {
			// TODO: handle exception
			JsonObject object = new JsonObject();
			object.addProperty(ArgsConfig.RESULT_CODE, ArgsConfig.RESPONSE_FAIL);
			object.addProperty(ArgsConfig.RESULT_DESC, "文件流为空！");
			System.out.println(object.toString());
			
			GenerateLog.outDebug("上传图片出错......");

			return new StringRepresentation(object.toString());
		}
	}
	
	
}
